<html>
<body>
Local: <br>
<video id="localVideo" autoplay></video><br>
Remote: <br>
<video id="remoteVideo" autoplay></video>

<script>
  // 仅仅用于控制哪一端的浏览器发起offer，#号后面有值的一方发起

  // 与信令服务器的WebSocket连接

  // stun和turn服务器
  var iceServer = null;

  // 创建PeerConnection实例 (参数为null则没有iceserver，即使没有stunserver和turnserver，仍可在局域网下通讯)
  var pc = new webkitRTCPeerConnection(iceServer);
  var pc2 = new webkitRTCPeerConnection(iceServer);
  // 发送ICE候选到其他客户端
  pc.onicecandidate = function(event){
    if (event.candidate !== null) {
      pc2.addIceCandidate(event.candidate);
      }
  };

  pc2.onicecandidate = function(event){
    if (event.candidate !== null) {
      pc.addIceCandidate(event.candidate);
    }
  };

  // 如果检测到媒体流连接到本地，将其绑定到一个video标签上输出
  pc2.onaddstream = function(event){
    document.getElementById('remoteVideo').src = URL.createObjectURL(event.stream);
  };

  // 发送offer和answer的函数，发送本地session描述
  var sendOfferFn = function(desc){
            pc.setLocalDescription(desc);
            pc2.setRemoteDescription(desc);
            pc2.createAnswer(sendAnswerFn, function (error) {
              console.log('Failure callback: ' + error);}
              );
          };

  var sendAnswerFn = function(desc){
    console.log(desc);
            pc2.setLocalDescription(desc);
            pc.setRemoteDescription(desc);
          };

  // 获取本地音频和视频流
  navigator.webkitGetUserMedia({
    "audio": true,
    "video": true
  }, function(stream){
    //绑定本地媒体流到video标签用于输出
    document.getElementById('localVideo').src = URL.createObjectURL(stream);
    //向PeerConnection中加入需要发送的流
    pc.addStream(stream);
    //如果是发起方则发送一个offer信令
    pc.createOffer(sendOfferFn, function (error) {
      console.log('Failure callback: ' + error);
    });

  }, function(error){
    //处理媒体流创建失败错误
    console.log('getUserMedia error: ' + error);
  });



</script>
</body>
</html>
